package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    
    // 构造方法
    public TcpEchoServer (int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    
    // 需要启动TCP
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService pool = Executors.newCachedThreadPool();// 线程池
        while(true){
            Socket clientSocket = serverSocket.accept(); //这个和客户端的socket 是建立了联系 是听筒和话筒的关系
//            Thread t = new Thread(()->{
//                try {
//                    processConnection(clientSocket);  // 这里不能快速去调用第二次accept,使用多线程
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d], 客户端上线\n", clientSocket.getInetAddress(),clientSocket.getPort());
        // 循环读取客户端的请求
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                // 1. 读取请求并解析,这里需要注意隐藏的约定, next读的时候要读到空白符才会结束.
                String request = scanner.next();
                // 2. 根据请求计算响应
                String response= process(request);
                // 3. 把响应返回给客户端
                    // 通过这种方式可以歇会 但是这种方式不方便给返回的响应中添加 \n
                //  outputStream.write(response.getBytes(),0,response.getBytes().length);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush(); // 同样的是刷新缓存区
                System.out.printf("[%s:%d] req: %s, resp: %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
            // 这边是需要对Client socket 进行close 操作.
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();

    }
}
